import axios from "axios";
import { useAuthStore } from '@/store/user';
import { useRouter } from "vue-router";
var base = "";

/*
 对axios进行二次封装 请求拦截器增加token 响应拦截器处理大数据
*/

// 初始化
const instance = axios.create();
// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // const token = store.state.token;
    const store = useAuthStore();
    const { token } = store;
    if (token) {
      //将token放到请求头发送给服务器,将tokenkey放在请求头中
      config.headers.Authorization = token;
      // config.headers.WWW-Authenticate = token;
      //也可以这种写法
      // config.headers['accessToken'] = Token;
      return config;
    }
  },
  function (error) {
    // Do something with request error
    // console.log(error)
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response;
}, function (error) {
  if (error.response.status === 401) {
    const store = useAuthStore();
    const { token } = store;
    if (token) {
      const router = useRouter();
      localStorage.clear();
      store.setAuth(false)
      router.push({
        name: "login",
      });
    }
  }
  // 对响应错误做点什么
  return Promise.reject(error);
});

export default instance;

export const POST = (url: string, params: any, responsetype?: any) => {
  return instance.post(`${base}${url}`, params, { responseType: responsetype });
};

export const GET = (url: string, params?: any) => {
  return instance.get(`${base}${url}`, { params: params });
};

export const PUT = (url: string, params: any) => {
  return instance.put(`${base}${url}`, params);
};

export const DELETE = (url: string, params: any) => {
  return instance.delete(`${base}${url}`, { data: params });
};

export const DOWNLOADFILE = (url: string, params: any, options: any, callback?: any) => {

  let download = (resp: any , options: any) => {
    let blob = new Blob([resp.data], { type: options.fileType ? options.fileType : 'application/octet-binary' })
    //创建下载的链接
    let href = window.URL.createObjectURL(blob)
    downloadBlob(href, options.fileName)
  }
  
  let downloadBlob = (blobUrl: string, fileName: string, revokeObjectURL?: any) => {
    let downloadElement = document.createElement('a')
    downloadElement.href = blobUrl
    //下载后文件名
    downloadElement.download = fileName
    document.body.appendChild(downloadElement)
    //点击下载
    downloadElement.click()
    //下载完成移除元素
    document.body.removeChild(downloadElement)
    if (revokeObjectURL == null || revokeObjectURL) {
     //释放掉blob对象
     window.URL.revokeObjectURL(blobUrl)
    }
   }

  instance.post(url, params, { responseType: 'arraybuffer' , onDownloadProgress: function (progressEvent) { //原生获取上传进度的事件
    if (callback){
      callback(progressEvent)
    }
    // if (progressEvent.lengthComputable) {
    //     //属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
    //     //如果lengthComputable为false，就获取不到progressEvent.total和progressEvent.loaded
    //   console.log( progressEvent.loaded / progressEvent.total * 100 )//实时获取上传进度
    // }
}}).then(resp => download(resp, options))
};

